package classloader;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @ClassName CustomerClassLoaderDemo
 * @Author ykx
 * @Date 2024/6/22 17:23
 * @Version 1.0
 */
public class CustomerClassLoaderDemo {
    public static void main(String[] args) throws ClassNotFoundException {
        String name = "classloader.MyTest";
        CustomerClassLoader loader = new CustomerClassLoader();
        Class<?> aClass = loader.findClass(name);
        System.out.println(aClass);
    }
}

class CustomerClassLoader extends ClassLoader {
    String Path = "C:\\Users\\Administrator\\Desktop\\";


    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        System.out.println("findclassොဩಗᤈ");
        Class<?> loadedClass = findLoadedClass(name);
        if (loadedClass != null) {
            return loadedClass;
        }
        byte[] bytes = null;
        try {
            bytes = getBytes(name);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (bytes != null) {
            System.out.println(bytes.length);
            Class<?> aClass = this.defineClass(name, bytes, 0, bytes.length);
            return aClass;
        } else {
            throw new ClassNotFoundException();
        }
    }

    private byte[] getBytes(String className) throws Exception {
        String s = className.replace(".", File.separator) + ".class";
        String FileUrl = Path + s;
        byte[] bytes;
        ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
        File file = new File(FileUrl);
        InputStream inputStream = new FileInputStream(file);
        int content;
        while ((content = inputStream.read()) != -1) {
            arrayOutputStream.write(content);
            arrayOutputStream.flush();
        }
        bytes = arrayOutputStream.toByteArray();
        return bytes;
    }
}